#!/bin/bash

container=$1
echo "检查容器是否运行"
restarterrorregex="(Context initialization failed|Error creating bean with name|This is very likely to create a memory leak|Exception in thread .main. java.lang.reflect.InvocationTargetException|Address already in use|Connection timed out for connection string|Failed to start component|Cannot allocate memory|Unable to start web server|A fatal exception has occurred|XXXXREGEX)"

dockerExists=$(docker inspect $container)
if [ $? -gt 0 ]; then
    echo "服务未启动 $container 容器不存在"
    exit 5
fi

#每5秒检查一次日志 ，共查5分钟，超过5分钟当失败
loop_interval=10
loop_count=60
for ((i=1;i<=$loop_count;i++))
do
    
    sleep ${loop_interval}
    echo "启动中...已等待 $(($loop_interval*$i))秒( 等待$((($loop_count-$i)*$loop_interval))秒后超时)"
    
    #日志有已知异常时报错， 进程即使启动 也不一定能正常服务 因此报错
    results=$(docker logs ${container} | grep -C 100 -P "$restarterrorregex")
    if [[ ${#results} !=  0 ]];then 
        echo "=========WARN,START FAILURE MESSAGE启动过程检查到致命问题,请查看日志排查=========\n\n" $results;exit "start appalication while check fail cauce match restarterrorregex in docker log" ;
        exit 1
    fi
    
    #启动进程中有重启过 也报错
    container_last_start_time=$(docker inspect ${container} |egrep "FinishedAt"|awk -F': ' '{print $2}' |awk -F\" '{print $2}')
    service_elapse=$(($(date +%s ) - $(date +%s -d $container_last_start_time)))
    #进程最后启动时间循环时间 ，说明循环检查期间有重启过 报错
    if [ $service_elapse -le $(($loop_interval*$i)) ]; then
        docker logs -t --tail 500 ${container}
        docker ps -a
        echo "运行报错，启动期间有自动重启过服务，请排查"
        exit 2   
    fi

    #日志中有 startup in 或 Started in  ，表明启动成功 # 因为 startup in 也有 应用启动完成，因此用 服务启动完成
    startOK=$(docker logs ${container} |egrep  "Started in|startup in|服务启动完成")
    if [ ${#startOK} !=  0 ];then 
     docker logs -t --tail 5000 ${container}
     echo "Jenkins部署完成 服务已启动:启动标志：${startOK}" ;
     exit 0
    fi
    
    
    #如果超时仍未启动 结循环并报错
    if [ $i -ge $loop_count ]; then 
         docker logs --tail 5000 ${container}
         echo "启动超时 超过5分钟仍未启动成功"
         exit 3
    fi
done

#loop 过程中已经退出， 本处以防有异常时退出。 如果 没有docker 进程 则报错
if [  $(docker ps |grep -w ${container} |grep -v 'grep'|awk '{print $1}') ]
then
  docker logs -t --tail 5000 ${container} 
  echo "Jenkins部署完成"
else
  echo "运行报错, 进程未正常运行，请排查"
  docker ps -a
  exit 4
fi